import base64
import json
from functools import wraps

import redis_lock

from util.redis_connect import RedisPoolConnect
from util.response_format import ResponseFormat

# 红包锁Redis连接池
redis_pool_lock = RedisPoolConnect(1)


def get_lock_middleware(fuc):
    """红包锁装饰器"""
    @wraps(fuc)
    def wrapper(*args, **kwargs):
        event = args[0]
        context = args[1]
        logger = context.getLogger()
        body = json.loads(base64.b64decode(event["body"]).decode().replace("'", '"'))
        red_envelope_id = body.get("redEnvelopeId")
        connect = redis_pool_lock.create_connect()
        # 根据红包id生成锁对象
        lock = redis_lock.Lock(connect, red_envelope_id, expire=30)
        response = ResponseFormat({"code": 400, "msg": "未知错误"}, 400).to_json()
        try:
            # 阻塞式获取锁，直到获取到锁才会执行后续代码
            if lock.acquire():
                response = fuc(*args, **kwargs)
        except Exception as e:
            logger.error(e)
            response = ResponseFormat({"code": 500, "msg": "服务器错误"}, 500).to_json()
        finally:
            lock.release()
        return response
    return wrapper
